package com.haoniu.common.service.impl;

import com.haoniu.common.service.QiNiuService;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.config.Config;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 描述:
 *
 * @author shilvfei
 * @create 2018-11-16 12:07
 */
@Service
public class QiNiuServiceImpl implements QiNiuService {

    @Value("${qiniu.file.accessKey}")
    private String accessKey;

    @Value("${qiniu.file.secretKey}")
    private String secretKey;

    @Value("${qiniu.file.bucket}")
    private String bucket;

    @Value("${file.base.url}")
    private String fileUrl;

    /**
     * 获取七牛云地址
     * @return
     */
    @Override
    public String getFileBaseUrl(){
        return fileUrl;
    }

    /**
     * 生成上传授权uptoken
     * */
    @Override
    public String getToken() {
        Config.ACCESS_KEY = accessKey;
        Config.SECRET_KEY = secretKey;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        // 请确保该bucket已经存在
        String bucketName = bucket;
        PutPolicy putPolicy = new PutPolicy(bucketName);
        String uptoken = null;
        try {
            uptoken = putPolicy.token(mac);
        } catch (AuthException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return uptoken;
    }

    //TODO 这个只是简单的上传功能 后续要结合Spring 的 MultipartFile 类进行进一步操作，
    //TODO 请后续开发的大神，对应完善起来

    /**
     * @param uploadFile 上传的文件
     * @param type       上传的图片类型 如：banner 。user
     * @return
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile uploadFile,String key) throws Exception {
        Config.ACCESS_KEY = accessKey;
        Config.SECRET_KEY = secretKey;
        Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
        // 请确保该bucket已经存在
        String bucketName = bucket;
        PutPolicy putPolicy = new PutPolicy(bucketName);
        String uptoken = putPolicy.token(mac);
        PutExtra extra = new PutExtra();
        PutRet ret = IoApi.Put(uptoken, key, uploadFile.getInputStream(),extra);
        //true /false 判断是否成功
        // System.out.println(ret.ok());
        //返回的图像路径名字
        // System.out.println(ret.getKey());
        //  System.out.println(ret.getHash());
        return key;
    }


}
